//
//  RHVideoManager.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/7/11.
//

#import "RHVideoManager.h"
#import  <AWSS3/AWSS3.h>

//#define access_key   @"AKIAU4H6JY7G3SSDYI5W"
//#define secret_key   @"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"
//#define bucket_name  @"bucketrenon-sit"
//#define region_name  @"us-west-2"
@interface RHVideoManager()
@property (nonatomic ,copy) NSURL *videoUrl;

@property (nonatomic, copy) NSString *accessKey;
@property (nonatomic, copy) NSString *secretKey;
@property (nonatomic, copy) NSString *backetName;
@property (nonatomic, copy) NSString *regionName;
@end
@implementation RHVideoManager
+ (RHVideoManager *)shareInstance{
    
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

-(void)uploadVideoWithUrl:(NSURL*)videoUrl coverImage:(UIImage*)coverImage;
{
    self.videoUrl = videoUrl;
    [QMUITips showLoadingInView:[UIApplication sharedApplication].keyWindow];
    [BaseModel startGetWithCompletionAPIKey:H_getS3Info argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            NSString *dataString = request.responseJSONObject[@"data"][@"encode"];
            NSString *encodeString =  [NSString base64Decode:dataString];
            NSDictionary *tokenDic = [encodeString jsonStringToDictionary];
            NSLog(@"---->%@",tokenDic);
            [self initAWSServerWithToken:tokenDic coverImage:coverImage];
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
    
    
   
}

-(void)initAWSServerWithToken:(NSDictionary*)tokenDic  coverImage:(UIImage*)coverImage;
{
    self.accessKey =  ValidNullData(tokenDic[@"accessKey"]);
    self.secretKey =  ValidNullData(tokenDic[@"secretKey"]);
    self.backetName = ValidNullData(tokenDic[@"bucketName"]);
    self.regionName = ValidNullData(tokenDic[@"regionName"]);
    NSLog(@"----->accessKey:%@",self.accessKey);
    NSLog(@"----->secretKey:%@",self.secretKey);
    NSLog(@"----->backetName:%@",self.backetName);
    NSLog(@"----->regionName:%@",self.regionName);
    AWSBasicSessionCredentialsProvider *provider = [[AWSBasicSessionCredentialsProvider alloc]
        initWithAccessKey:self.accessKey secretKey:self.secretKey sessionToken:@""];
    
    
//    AWSEndpoint *endpoint = [[AWSEndpoint alloc] initWithRegion:AWSRegionUSWest2
//     service:AWSServiceS3 URL:[NSURL URLWithString:url]];
//
//    AWSServiceConfiguration *serviceConfig = [[AWSServiceConfiguration alloc]
//     initWithRegion:AWSRegionUSWest2 endpoint:endpoint credentialsProvider:provider];
    
    //上传前配置
    AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSWest2 credentialsProvider:provider];
    
    [AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;
    AWSS3TransferUtility *S3TransferUtility = [AWSS3TransferUtility
     defaultS3TransferUtility:^(NSError * _Nullable error) {
        if (error) {
            NSLog(@"------创建上传实例失败:%@",error);
        }else{
            NSLog(@"----->创建上传实例成功");
        }
    }];
    
   
    
    [QMUITips showLoading:@"压缩图片...".rh_localized inView:[UIApplication sharedApplication].keyWindow];
   
    //压缩到500K
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData *imageData = [self compressImageQuality:coverImage toByte:1000];
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTipsInView:[UIApplication sharedApplication].keyWindow];
            
            //先上传缩略图
            [QMUITips showLoading:@"上传图片...".rh_localized inView:[UIApplication sharedApplication].keyWindow];
            [self uploadCoverImage:S3TransferUtility imageData:imageData];
        });
    });
    
    
    
    
    
    
    // 或
//    AWSS3TransferUtility *S3TransferUtility = [AWSS3TransferUtility defaultS3TransferUtility];

    //---------第2种
//    [AWSServiceManager defaultServiceManager].defaultServiceConfiguration = serviceConfig;
//    AWSS3 *S3 = [AWSS3 defaultS3];
//
//    AWSS3PutObjectRequest *request = [[AWSS3PutObjectRequest alloc] init];
//    request.key = @"videoFile.mp4";
//    request.body = self.videoUrl;
//    request.bucket = bucketName;
//    // 上传进度
//    request.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend){
//        
//    };
//    
//    [S3 putObject:request completionHandler:^(AWSS3PutObjectOutput * _Nullable response, NSError * _Nullable error) {
//      
//    }];


}

#pragma mark ----- 上传封面
-(void)uploadCoverImage:(AWSS3TransferUtility*)S3TransferUtility  imageData:(NSData*)imageData
{
    // 上传进度
    AWSS3TransferUtilityUploadExpression *expression = [AWSS3TransferUtilityUploadExpression new];
    expression.progressBlock = ^(AWSS3TransferUtilityTask *task, NSProgress *progress) {
        
        NSLog(@"------->图片上传进度:%f",progress.completedUnitCount*1.0/progress.totalUnitCount);
        dispatch_async(dispatch_get_main_queue(), ^{
            NSNumber *progressValue = [NSNumber numberWithFloat:progress.completedUnitCount*1.0/progress.totalUnitCount];
            [[NSNotificationCenter defaultCenter]postNotificationName:VIDEO_UPLOADING_NOTIFICATION object:progressValue];
        });
        
    };
   
    NSString *url = [NSString stringWithFormat:@"https://%@.s3.amazonaws.com",self.backetName];
    //文件名
    NSString *fileName = [NSString stringWithFormat:@"%@-%@.jpg",[NSDate dateStringWithTimeInterval:[[NSDate date]timeIntervalSince1970] formatter:@"yyyyMMddHHmmss"],[NSString generateRandomLetter:16]];
    NSString *imageLink = [NSString stringWithFormat:@"%@/%@",url,fileName];
    NSLog(@"----->图片链接:%@",imageLink);
    
    //上传data
    
    [[S3TransferUtility uploadData:imageData bucket:self.backetName key:fileName contentType:@"image/jpg" expression:expression completionHandler:^(AWSS3TransferUtilityUploadTask * _Nonnull task, NSError * _Nullable error) {
        NSLog(@"------->上传图片完毕");
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTipsInView:[UIApplication sharedApplication].keyWindow];
            [[NSNotificationCenter defaultCenter]postNotificationName:VIDEO_BEGIN_UPLOAD_NOTIFICATION object:[UIImage imageWithData:imageData]];
            [self uploadVideo:S3TransferUtility coverLink:imageLink];
        });
        
    }] continueWithBlock:^id _Nullable(AWSTask<AWSS3TransferUtilityUploadTask *> * _Nonnull t) {
        if (t.error) {
            // ERROR
            NSLog(@"uploadFile error:%@",t.error);
            dispatch_async(dispatch_get_main_queue(), ^{
                [QMUITips hideAllTipsInView:[UIApplication sharedApplication].keyWindow];
            });
        }
        if (t.result) {
            // Do something with uploadTask
            NSLog(@"uploadFile:%@",t.result);
        }
        return nil;
    }];
}

#pragma mark ----- 上传视频
-(void)uploadVideo:(AWSS3TransferUtility*)S3TransferUtility coverLink:(NSString*)coverLink
{
    // 上传进度
    AWSS3TransferUtilityUploadExpression *expression = [AWSS3TransferUtilityUploadExpression new];
    expression.progressBlock = ^(AWSS3TransferUtilityTask *task, NSProgress *progress) {
        
        NSLog(@"------->视频上传进度:%f",progress.completedUnitCount*1.0/progress.totalUnitCount);
        dispatch_async(dispatch_get_main_queue(), ^{
            NSNumber *progressValue = [NSNumber numberWithFloat:progress.completedUnitCount*1.0/progress.totalUnitCount];
            [[NSNotificationCenter defaultCenter]postNotificationName:VIDEO_UPLOADING_NOTIFICATION object:progressValue];
        });
        
    };
    // AWSS3TransferUtility对象
    // 上传NSData
//    [[transferUtility uploadData:data bucket:bucket key:key contentType:contentType
//     expression:expression completionHandler:^(AWSS3TransferUtilityUploadTask * _Nonnull task, NSError * _Nullable error) {
//        // 完成回调
//        !completionHandler ?: completionHandler(error);
//    }] continueWithBlock:^id(AWSTask *task) {
//        if (task.error) {
//            NSLog(@"AWSTask.error: %@", task.error);
//        }
//        if (task.result) {
//            NSLog(@"AWSTask.result: %@", task.result);
//        }
//        return nil;
//    }];
    
    // 上传URL
//    [[S3TransferUtility uploadFile:self.videoUrl bucket:bucketName key:@"test.mp4" contentType:@"video/mp4"
//     expression:expression completionHandler:^(AWSS3TransferUtilityUploadTask * _Nonnull task, NSError * _Nullable error) {
//        // 完成回调
//        NSLog(@"------->上传完毕");
//
//    }] continueWithBlock:^id(AWSTask *task) {
//        if (task.error) {
//            NSLog(@"AWSTask.error: %@", task.error);
//        }
//        if (task.result) {
//            NSLog(@"AWSTask.result: %@", task.result);
//        }
//        return nil;
//    }];

    
    NSString *url = [NSString stringWithFormat:@"https://%@.s3.amazonaws.com",self.backetName];
    //文件名
    NSString *fileName = [NSString stringWithFormat:@"%@-%@.mp4",[NSDate dateStringWithTimeInterval:[[NSDate date]timeIntervalSince1970] formatter:@"yyyyMMddHHmmss"],[NSString generateRandomLetter:16]];
    NSString *videoLink = [NSString stringWithFormat:@"%@/%@",url,fileName];
    NSLog(@"----->视频链接:%@",videoLink);
    
    //上传data
    NSData *videoData = [NSData dataWithContentsOfURL:self.videoUrl];
    
    [[S3TransferUtility uploadData:videoData bucket:self.backetName key:fileName contentType:@"video/mp4" expression:expression completionHandler:^(AWSS3TransferUtilityUploadTask * _Nonnull task, NSError * _Nullable error) {
        NSLog(@"------->上传完毕");
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self commitVideo:videoLink coverUrl:coverLink];
        });
        
    }] continueWithBlock:^id _Nullable(AWSTask<AWSS3TransferUtilityUploadTask *> * _Nonnull t) {
        if (t.error) {
            // ERROR
            NSLog(@"uploadFile error:%@",t.error);
        }
        if (t.result) {
            // Do something with uploadTask
            NSLog(@"uploadFile:%@",t.result);
        }
        return nil;
    }];
}


#pragma mark --------  案例分享 提交表单
-(void)commitVideo:(NSString*)videoUrl coverUrl:(NSString*)coverLink
{
    NSMutableDictionary  *para = [NSMutableDictionary dictionaryWithDictionary:@{
        @"cover":coverLink,
        @"videoLink":videoUrl
    }];
    [para addEntriesFromDictionary:self.uploadPara];
    [BaseModel startWithCompletionAPIKey:H_addCaseStudyVideo argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [[NSNotificationCenter defaultCenter]postNotificationName:VIDEO_UPLOAD_FINISH_NOTIFICATION object:nil];
//            [QMUITips showSucceed:@"分享成功！审核通过即可查看".rh_localized inView:[UIApplication sharedApplication].keyWindow hideAfterDelay:1.5];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [[NSNotificationCenter defaultCenter]postNotificationName:VIDEO_UPLOAD_FINISH_NOTIFICATION object:nil];
//            });
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
    
}



#pragma mark ------ 压缩图片质量   maxLength  单位: kb
- (NSData *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    
     CGFloat compression = 1;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length / 1024 > maxLength && compression > 0) {
         compression -= 0.05;
         // When compression less than a value, this code dose not work
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"====>压缩了一次后: %ld k",(long)(data.length / 1024));
     }
     return data;
}

@end
